package com.xzx.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.xzx.server.pojo.Employee;
import com.xzx.server.pojo.MailConstants;
import com.xzx.server.pojo.MailLog;
import com.xzx.server.service.IEmployeeService;
import com.xzx.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 *
 * @author xzx
 * @since 2022/5/2
 */
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时入伍
     * 10秒执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void mailTask() {
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", MailConstants.DELIVERING).lt("tryTime",
                LocalDateTime.now()));
        list.forEach(mailLog -> {
            //重试次数超过最大尝试次,更新状态为投递失败，不再重新发送消息
            if (mailLog.getCount() >= MailConstants.MAX_TRY_COUNT) {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status", MailConstants.FAILURE)
                        .eq("msgId", mailLog.getMsgId()));
            } else {
                //更新次数，时间
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("count", mailLog.getCount() + 1)
                        .set("updateTime", LocalDateTime.now())
                        .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                        .eq("msgId", mailLog.getMsgId()));
                Employee emp = employeeService.getEmployee(mailLog.getEid()).get(0);
                //重新发送消息
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAEM, emp,
                        new CorrelationData(mailLog.getMsgId()));
            }

        });
    }
}
